package cn.kimming.wms.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.kimming.wms.dao.ISystemMenuDAO;
import cn.kimming.wms.domain.Employee;
import cn.kimming.wms.domain.SystemMenu;
import cn.kimming.wms.excep.ObjectIsUsedException;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.service.ISystemMenuService;
import cn.kimming.wms.util.UserContext;
import cn.kimming.wms.vo.SystemMenuVO;

@Service("systemMenuService")
public class SystemMenuServiceImpl implements ISystemMenuService {

	@Autowired
	private ISystemMenuDAO systemMenuDAO;
	
	@Override
	public void save(SystemMenu obj) {
		systemMenuDAO.save(obj);
	}

	@Override
	public void update(SystemMenu obj) {
		systemMenuDAO.update(obj);
	}

	@Override
	public void delete(Long id) {
		List<SystemMenu> children = systemMenuDAO.listByParentId(id);
		if (children.size() > 0) {
			throw new ObjectIsUsedException();
		}
		systemMenuDAO.delete(systemMenuDAO.get(id));
	}

	@Override
	public SystemMenu get(Long id) {
		return systemMenuDAO.get(id);
	}

	@Override
	public List<SystemMenu> list() {
		return systemMenuDAO.list();
	}

	@Override
	public List<SystemMenu> query(QueryObject qo) {
		return systemMenuDAO.query(qo);
	}

	@Override
	public List<SystemMenu> listChildren() {
		return systemMenuDAO.listChildren();
	}
	
	@Override
	public List<SystemMenuVO> listParents(Long parentId) {
		List<SystemMenuVO> parents = new ArrayList();
		SystemMenu systemMenu = systemMenuDAO.get(parentId);
		addParents(parents, systemMenu);
		//翻转集合
		Collections.reverse(parents);
		return parents;
	}
	
	private void addParents(List<SystemMenuVO> parents, SystemMenu parent) {
		if (parent != null) {
			SystemMenuVO vo = new SystemMenuVO();
			vo.setId(parent.getId());
			vo.setName(parent.getName());
			parents.add(vo);
			addParents(parents, parent.getParent());
		}
	}

	@Override
	public List<SystemMenu> loadMenus(String parentSn) {
		SystemMenu parent = systemMenuDAO.getBySn(parentSn);
		if (parent != null) {
			Employee user = UserContext.getUser();
			if (user.isAdmin()) {
				//超级用户, 显示所有子菜单
				return systemMenuDAO.listByParentSn(parentSn);
			} else {
				//普通用户
				return systemMenuDAO.listByParentSnAndRole(parentSn, user.getRoles());
			}
		}
		return Collections.EMPTY_LIST;
	}

	
}
